package com.geor.gcv.core.ui;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * swing面板,测试用,绘制Image数组对象图片
 * 
 * @author geor.lusongnan
 *
 */
public class ImagePanel extends JPanel implements Observer {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String name;
	private int width;
	private int height;
	protected List<Image> images = new ArrayList<Image>();
	protected Observable observable;
	private JFrame frame;

	public ImagePanel() {
		this("default", 500, 500, null);
		initFrame();
	}

	public ImagePanel(String name, int width, int height, Observable observable) {
		super();
		this.name = name;
		this.width = width;
		this.height = height;
		observable.addObserver(this);
		this.observable = observable;
		this.setBackground(Color.GRAY);
		initFrame();
	}

	private void initFrame() {
		frame = new JFrame(name);
		frame.setSize(width, height);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.add(this);
	}

	/** 绘制显示图片面板 */
	public void init() {
		frame.setVisible(true);
	}

	public void close() {
		frame.setVisible(false);
	}

	public List<Image> getImages() {
		return images;
	}
	
	public void setTitle(String title) {
		frame.setTitle(title);
	}

	@Override
	protected void paintComponent(Graphics g) {
		super.paintComponent(g);
		if (images != null) {
			int height = 0;
			int w = 0;
			int newW = 0;
			int oldW = 0;
			for (int i = 0; i < images.size(); i++) {
				if (images.get(i) != null) {
					newW = images.get(i).getWidth(null) > oldW ? images.get(i).getWidth(null) : oldW;
					
					if (height + 100 > this.height) {
						height = 0;
						w += newW;
					}
					g.drawImage(images.get(i), w, height, images.get(i).getWidth(null),
							images.get(i).getHeight(null) - 2, null);
					height += images.get(i).getHeight(null);
					
					oldW = newW;
				}
				
			}
		}
	}

	public int getWidth() {
		return width;
	}

	public void setWidth(int width) {
		this.width = width;
	}

	public int getHeight() {
		return height;
	}

	public void setHeight(int height) {
		this.height = height;
	}

	public void setImages(List<Image> images) {
		this.images = images;
	}

	@Override
	public void update(Observable o, Object arg) {
		if (arg instanceof PanelObservable) {
			PanelObservable observer = (PanelObservable) arg;
			for (int i = 0; i < observer.getImage().length; i++) {
				images.add(observer.getImage()[i]);
			}
			repaint();
		}
	}

}
